#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/21 11:28
# @Author : 闫峰
# @File    : get_sku_dynamic_inventory.py
from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database

db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")

def get_good_num(sku):
    is_group_sql = """SELECT is_group FROM test_zhcxkj_center_product.rb_product WHERE sku=%s;"""
    is_group_sql_res = db.fetch_all(is_group_sql, (sku,))
    if is_group_sql_res:
        if is_group_sql_res[0]['is_group'] == 0:
            filter_good_num = """
            SELECT SUM(good_num) good_num FROM test_zhcxkj_center_product.dynamic_inventory WHERE sku=%s;
            """
            res1 = db.fetch_all(filter_good_num, (sku,))
            if res1[0].get('good_num'):
                # print(f"{sku}动态库存：{res1[0].get('good_num')}")
                return res1[0].get('good_num')
            else:
                # print(f"{sku}动态库存：0")
                return 0
        else:
            get_child_sku = "SELECT sku,sku_num FROM test_zhcxkj_center_product.rb_product_group_sku " \
                            "WHERE group_sku=%s;"
            get_child_sku_res = db.fetch_all(get_child_sku, (sku,))

            if get_child_sku_res:
                sku_list = []
                for child in get_child_sku_res:
                    filter_good_num = """
                        SELECT SUM(good_num) good_num FROM test_zhcxkj_center_product.dynamic_inventory 
                        WHERE sku = %s  group by sku;"""
                    filter_good_num_res = db.fetch_all(filter_good_num, (child.get('sku'),))
                    if filter_good_num_res:
                        good_num = filter_good_num_res[0].get('good_num')
                    else:
                        good_num = 0
                    dongtaikucun = int(good_num / (child.get('sku_num')))
                    sku_list.append((child.get('sku'), dongtaikucun))
                min_sku = sorted(sku_list, key=lambda x: x[1], reverse=False)[0]
                finally_good_num = min_sku[1]
                # print(f"{sku}动态库存：{finally_good_num}")
                return finally_good_num
            else:
                # print(f"{sku}在rb_product_group_sku表没查询到子sku")
                return 0

if __name__ == '__main__':
    print(get_good_num("17216885"))